import { createAppSlice } from "@/lib/createAppSlice";
import { PayloadAction } from "@reduxjs/toolkit";

export interface LoginState {
    principal: {
        accountNonExpired: boolean,
        accountNonLocked: boolean,
        credentialsNonExpired: boolean,
        authorities: string[],
        enabled: boolean,
    },
    userInfo: {
        username: string,
        email: string,
        user_id: number | undefined,
    }
}

const initialState: LoginState = {
    principal: {
        accountNonExpired: false,
        accountNonLocked: false,
        credentialsNonExpired: false,
        authorities: [],
        enabled: false
    },
    userInfo: {
        username: "",
        email: "",
        user_id: undefined
    }
}

export const loginSlice = createAppSlice({
    name: "login",
    initialState,
    reducers: (create) => ({
        setUserData: create.reducer((state, action: PayloadAction<LoginState>) => {
            state.userInfo = action.payload.userInfo
            state.principal = action.payload.principal
        }),
        updateUserName: create.reducer((state, action: PayloadAction<string>) => {
            state.userInfo.username = action.payload
        })
    }),
    selectors: {
        selectUserDetail: (login) => login.userInfo
    }
})

export const { setUserData, updateUserName } = loginSlice.actions

export const { selectUserDetail } = loginSlice.selectors
